package org.jeecg.glr.iframe.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.SysConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SysUtil;
import org.jeecg.glr.entity.GlrVideo;
import org.jeecg.glr.entity.GlrVideoYs;
import org.jeecg.glr.iframe.service.IGlrIframeVideoMonitoringService;
import org.jeecg.glr.iframe.util.AjaxJson;
import org.jeecg.glr.service.IGlrVideoService;
import org.jeecg.glr.service.IGlrVideoYsService;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.glr.util.HttpRequestUtil;
import org.jeecg.glr.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.jeecg.common.constant.CommonConstant.St_Access_Token;

/**
 *iframe使用
 * 视频播放功能
 */
@Slf4j
@Controller
@RequestMapping("/iframeGlr/videoMonitoring")
public class GlrIframeVideoMonitoring extends JeecgController<GlrVideo, IGlrVideoService> {

    @Autowired
    private IGlrVideoService glrVideoService;

    @Autowired
    private IGlrVideoYsService glrVideoYsService;

    @Autowired
    private IGlrIframeVideoMonitoringService glrIframeVideoMonitoringService;

    @Value("${glr.path.vue_url}")
    private String vue_url;
    /**
     * @param modelAndView
     * @return
     */
    @RequestMapping("/html")
    public ModelAndView ftl(ModelAndView modelAndView) {
        modelAndView.setViewName("demo3");
        List<String> userList = new ArrayList<String>();
        userList.add("admin");
        userList.add("user1");
        userList.add("user2");
        log.info("--------------test--------------");
        modelAndView.addObject("userList", userList);
        return modelAndView;
    }

    @RequestMapping("/index1")
    public ModelAndView index1(ModelAndView modelAndView, HttpServletRequest request) throws Exception {
        modelAndView.setViewName("/glrTemplates/VideoMonitoring/index");
        glrIframeVideoMonitoringService.updateUserInfo(request);
        return modelAndView;
    }

    /**
     * 智慧物流监控模版
     * @param modelAndView
     * @return
     */
    @RequestMapping("/index2")
    public ModelAndView index2(ModelAndView modelAndView, HttpServletRequest request)throws Exception {
        modelAndView.setViewName("/bigscreen/template2/index");
        glrIframeVideoMonitoringService.updateUserInfo(request);
        return modelAndView;
    }

    /**
     * 监控管理
     * @param modelAndView
     * @return
     */
    @RequestMapping("/index")
    public String list(Model model, HttpServletRequest request) throws Exception {
        try{
            LoginUser loginUser=glrIframeVideoMonitoringService.updateUserInfo(request);
            if (loginUser==null){
                return "redirect:"+vue_url;
            }
        }catch (Exception ex){
            return "redirect:"+vue_url;
        }
        model.addAttribute("AccessToken",request.getParameter(St_Access_Token));
        return "/glrTemplates/VideoMonitoring/index";
    }


    @RequestMapping("/videoYSList")
    @ResponseBody
    public Result<?> videoYSList(HttpServletRequest request, HttpServletResponse response)
    {
        try{
            LoginUser loginUser= glrIframeVideoMonitoringService.updateUserInfo(request);

            String stsql ="select \n" +
                    "a.name,a.id,b.id as id1,a.equipment_serial,a.equipment_channel,a.equipment_url\n" +
                    "from glr_video a\n" +
                    "LEFT JOIN glr_video_ys b on a.video_ys_code=b.code";
            if(loginUser!=null){
                if(!loginUser.getUserType().equals(SysConstant.SYS_USER_TYPE_0)&&!loginUser.getUserType().equals(SysConstant.SYS_USER_TYPE_ADMIN)){
                    stsql=stsql+" where a.sys_company_code='"+ loginUser.getSysCompanyCode()+"'";
                }
            }

            List<GlrVideoYs> glrVideoYsList=glrVideoYsService.list();
            Map<String,GlrVideoYs> glrVideoYsMap=new HashMap<>();
            for (GlrVideoYs glrVideoYs : glrVideoYsList) {
                String stToken = glrVideoYsService.getToken(glrVideoYs);
                glrVideoYs.setAccessToken(stToken);
                glrVideoYsMap.put(glrVideoYs.getId(), glrVideoYs);
            }

            //GlrVideoYs glrVideoYs=glrVideoYsService.getById(GLRConstant.GLR_VIDEO_YS_GAOTAI_ID);
            List<Map<String, Object>> videoList = glrVideoYsService.doGetListForJdbc(stsql);
            for (Map<String, Object> o : videoList){
                String stid1 = o.get("id1").toString(); //serverId
                glrVideoYsMap.get(stid1);
                //GlrVideoYs glrVideoYs=glrVideoYsService.getById(stid1);
                GlrVideoYs glrVideoYs=glrVideoYsMap.get(stid1);

                String stid = o.get("id").toString();
                GlrVideo domain=glrVideoService.getById(stid);
                glrVideoYsService.updateGlrVideoStatus(domain,glrVideoYs);
                o.put("equipmentStatus",domain.getEquipmentStatus());

                Object equipment_url=o.get("equipment_url");
                if (StringUtil.isNotEmpty(equipment_url)){
                    JSONObject stAddress = JSONObject.parseObject(equipment_url.toString());
                    o.put("hlsHd", stAddress.get("hlsHd"));
                    o.put("hls", stAddress.get("hls"));
                    o.put("rtmp", stAddress.get("rtmp"));
                    o.put("rtmpHd", stAddress.get("rtmpHd"));
                }else{
                    //String stToken = glrVideoYsService.getToken(glrVideoYs);
                    JSONObject stAddress = glrVideoYsService.getAddress(stid, glrVideoYs.getAccessToken());
                    o.put("hlsHd", stAddress.get("hlsHd"));
                    o.put("hls", stAddress.get("hls"));
                    o.put("rtmp", stAddress.get("rtmp"));
                    o.put("rtmpHd", stAddress.get("rtmpHd"));
                }
            }
            return Result.ok(videoList);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping("/videoYS")
    @ResponseBody
    public Result<?> videoYS(HttpServletRequest request, HttpServletResponse response,@RequestBody(required = true) Map<String, Object> map)
    {
        try{
            Object stdeviceSerial = map.get("deviceSerial");
            String stDEVICESERIAL = stdeviceSerial.toString();
            String stsql = "select a.id as t_b_video_id,b.id as t_b_video_ys_id from glr_video a left join glr_video_ys b on a.video_ys_code=b.code where a.equipment_serial='"
                    + stDEVICESERIAL + "'";
            List<Map<String, Object>> videoList = glrVideoYsService.doGetListForJdbc(stsql);
            String st_t_b_video_id = "";
            String st_t_b_video_ys_id = "";
            for (Map<String, Object> o : videoList)
            {
                st_t_b_video_ys_id = o.get("t_b_video_ys_id").toString();
                st_t_b_video_id = o.get("t_b_video_id").toString();
            }

            //GlrVideoYs glrVideoYs=glrVideoYsService.getById(GLRConstant.GLR_VIDEO_YS_GAOTAI_ID);
            String stACCESSTOKEN = glrVideoYsService.getToken(st_t_b_video_ys_id);
            //String stACCESSTOKEN = glrVideoYsService.getToken(glrVideoYs);
            //String stACCESSTOKEN="at.9tjm5ek33cvky5q7bvajpywr72mn98ta-7eelirk6nx-0silohe-n7hocksrw";
            Object sttype = map.get("type");
            //System.out.println("==sttype" + sttype);
            if("start".equals(sttype)){
                Object stdirection = map.get("direction");
                Object stspeed = map.get("speed");
                //System.out.println("==stdeviceSerial" + stdeviceSerial + "==stdirection" + stdirection + "==stspeed" + stspeed);
                String stCHANNELNO = "1";
                String stDIRECTION = stdirection.toString();
                String stSPEED = stspeed.toString();
                String url = HttpRequestUtil.YS_DEVICE_START_URL.replaceAll("ACCESSTOKEN", stACCESSTOKEN)
                        .replaceAll("DEVICESERIAL", stDEVICESERIAL).replaceAll("CHANNELNO", stCHANNELNO)
                        .replaceAll("DIRECTION", stDIRECTION).replaceAll("SPEED", stSPEED);
                com.alibaba.fastjson.JSONObject json = HttpRequestUtil.httpRequest(url, "POST", null);
                //System.out.println(json.toString());
                if(json.get("code").toString().equals("200")){
                    return Result.ok("ok");
                }
                return Result.error("error");
            }else if("stop".equals(sttype)){
                //System.out.println("==stdeviceSerial" + stdeviceSerial);
                String stCHANNELNO = "1";
                String url = HttpRequestUtil.YS_DEVICE_STOP_URL.replaceAll("ACCESSTOKEN", stACCESSTOKEN)
                        .replaceAll("DEVICESERIAL", stDEVICESERIAL).replaceAll("CHANNELNO", stCHANNELNO);
                com.alibaba.fastjson.JSONObject json = HttpRequestUtil.httpRequest(url, "POST", null);
                //System.out.println(json.toString());

                if(json.get("code").toString().equals("200")){
                    return Result.ok("ok");
                }
                return Result.error("error");

            }else if("mirror".equals(sttype)){
                Object stcommand = map.get("command");
                //System.out.println("==stdeviceSerial" + stdeviceSerial + "==stcommand" + stcommand);
                String stCHANNELNO = "1";
                String stCOMMAND = stcommand.toString();
                String url = HttpRequestUtil.YS_DEVICE_MIRROR_URL.replaceAll("ACCESSTOKEN", stACCESSTOKEN)
                        .replaceAll("DEVICESERIAL", stDEVICESERIAL).replaceAll("CHANNELNO", stCHANNELNO)
                        .replaceAll("COMMAND", stCOMMAND);
                com.alibaba.fastjson.JSONObject json = HttpRequestUtil.httpRequest(url, "POST", null);
                //System.out.println(json.toString());
                if(json.get("code").toString().equals("200")){
                    return Result.ok("ok");
                }
                return Result.error("error");

            }else if("addPointer".equals(sttype)){
                Object stpresetName = map.get("presetName");
                String stCHANNELNO = "1";
                String url = HttpRequestUtil.YS_DEVICE_PRESET_ADD_URL.replaceAll("ACCESSTOKEN", stACCESSTOKEN)
                        .replaceAll("DEVICESERIAL", stDEVICESERIAL).replaceAll("CHANNELNO", stCHANNELNO);
                com.alibaba.fastjson.JSONObject json = HttpRequestUtil.httpRequest(url, "POST", null);
                //System.out.println(json.toString());
                if(json.get("code").toString().equals("200")){
                    JSONObject json1 = JSONObject.parseObject(json.get("data").toString());
                    String index = json1.get("index").toString();

                    GlrVideo video = glrVideoService.getById(st_t_b_video_id);
                    String st1 = video.getEquipmentPreset();
                    if(StringUtil.isEmpty(st1)){
                        JSONArray jArray = new JSONArray();
                        JSONObject jsonObject_1 = new JSONObject();
                        jsonObject_1.put("PresetName", stpresetName);
                        jsonObject_1.put("PresetIndex", index);
                        jArray.add(jsonObject_1);
                        video.setEquipmentPreset(jArray.toString());
                        glrVideoService.saveOrUpdate(video);
                    }else {
                        JSONArray jArray = null;
                        try
                        {
                            jArray = JSONArray.parseArray(st1);
                        }
                        catch (Exception ex)
                        {
                            jArray = new JSONArray();
                        }
                        JSONObject jsonObject_1 = new JSONObject();
                        jsonObject_1.put("PresetName", stpresetName);
                        jsonObject_1.put("PresetIndex", index);
                        jArray.add(jsonObject_1);
                        video.setEquipmentPreset(jArray.toString());
                        glrVideoService.saveOrUpdate(video);
                    }
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("index", index);
                    return Result.ok(jsonObject);
                }
                return Result.error("没有");

            }else if("GetPresetPointList".equals(sttype)){
                GlrVideo video = glrVideoService.getById(st_t_b_video_id);
                String st1 = video.getEquipmentPreset();
                try
                {
                    if(StringUtil.isNotEmpty(st1))
                    {
                        JSONArray jArray = JSONArray.parseArray(st1);
                        /*
                         * JSONArray jArray = new JSONArray(); for(int
                         * i=0;i<6;i++){ JSONObject jsonObject = new
                         * JSONObject(); jsonObject.put("PresetName", "test"+i);
                         * jsonObject.put("PresetIndex", i+1);
                         * jArray.add(jsonObject); }
                         */
                        return Result.ok(jArray);
                    }
                }catch (Exception e){

                }
                return  Result.error("找不到");
            }else if("ClearPresetPoint".equals(sttype)){
                Object oindex = map.get("index");
                if(StringUtil.isNotEmpty(oindex)){
                    String stCHANNELNO = "1";
                    String stINDEX = oindex.toString();
                    String url = HttpRequestUtil.YS_DEVICE_PRESET_CLEAR_URL.replaceAll("ACCESSTOKEN", stACCESSTOKEN)
                            .replaceAll("DEVICESERIAL", stDEVICESERIAL).replaceAll("CHANNELNO", stCHANNELNO)
                            .replaceAll("INDEX", stINDEX);
                    com.alibaba.fastjson.JSONObject json = HttpRequestUtil.httpRequest(url, "POST", null);
                    //System.out.println(json.toString());
                    if(json.get("code").toString().equals("200")){
                        GlrVideo video = glrVideoService.getById(st_t_b_video_id);
                        String st1 = video.getEquipmentPreset();
                        if(StringUtil.isNotEmpty(st1)){
                            JSONArray jArray = JSONArray.parseArray(st1);
                            if(jArray.size() > 0){
                                JSONArray jArrayNew = new JSONArray();
                                for (int i = 0; i < jArray.size(); i++)
                                {
                                    // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                                    JSONObject job = jArray.getJSONObject(i);
                                    String stPresetIndex = job.get("PresetIndex").toString();
                                    if(stINDEX.equals(stPresetIndex))
                                    {
                                    }
                                    else
                                    {
                                        JSONObject jsonObject_1 = new JSONObject();
                                        jsonObject_1.put("PresetName", job.get("PresetName"));
                                        jsonObject_1.put("PresetIndex", stPresetIndex);
                                        jArrayNew.add(jsonObject_1);
                                    }
                                }
                                video.setEquipmentPreset(jArrayNew.toString());
                                glrVideoService.saveOrUpdate(video);
                                return Result.ok("ok");
                            }
                        }
                    }
                }
                return  Result.error("error");

            }else if("SetPresetPoint".equals(sttype)){
                Object oindex = map.get("index");
                if(StringUtil.isNotEmpty(oindex))
                {
                    String stCHANNELNO = "1";
                    String stINDEX = oindex.toString();
                    String url = HttpRequestUtil.YS_DEVICE_PRESET_MOVE_URL.replaceAll("ACCESSTOKEN", stACCESSTOKEN)
                            .replaceAll("DEVICESERIAL", stDEVICESERIAL).replaceAll("CHANNELNO", stCHANNELNO)
                            .replaceAll("INDEX", stINDEX);
                    com.alibaba.fastjson.JSONObject json = HttpRequestUtil.httpRequest(url, "POST", null);
                    //System.out.println(json.toString());
                    if(json.get("code").toString().equals("200"))
                    {
                        return Result.ok("ok");
                    }
                }
                return  Result.error("error");
            }else if("CapturePic".equals(sttype)){
                String stCHANNELNO = "1";
                String url = HttpRequestUtil.YS_DEVICE_CAPTURE_URL.replaceAll("ACCESSTOKEN", stACCESSTOKEN)
                        .replaceAll("DEVICESERIAL", stDEVICESERIAL).replaceAll("CHANNELNO", stCHANNELNO);
                com.alibaba.fastjson.JSONObject json = HttpRequestUtil.httpRequest(url, "POST", null);
                //System.out.println(json.toString());
                if(json.get("code").toString().equals("200"))
                {
                    JSONObject json1 = JSONObject.parseObject(json.get("data").toString());
                    String picUrl = json1.get("picUrl").toString();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("picUrl", picUrl);
                    return Result.ok(jsonObject);
                }
                return  Result.error("error");
            }


        }catch (Exception e){

        }
        return  Result.ok("1212");
    }

    /**
     * 人脸地图
     * @param modelAndView
     * @return
     */
    @RequestMapping("/index4")
    public ModelAndView index4(ModelAndView modelAndView, HttpServletRequest request) throws Exception{
        modelAndView.setViewName("/bigscreen/template4/index");
        glrIframeVideoMonitoringService.updateUserInfo(request);
        return modelAndView;
    }

    /**
     * 人脸检测
     * @param modelAndView
     * @return
     */
    @RequestMapping("/index5")
    public ModelAndView index5(ModelAndView modelAndView, HttpServletRequest request) throws Exception{
        modelAndView.setViewName("/bigscreen/template5/index");
        glrIframeVideoMonitoringService.updateUserInfo(request);
        return modelAndView;
    }

    /**
     * 人脸列表
     * @param modelAndView
     * @return
     */
    @RequestMapping("/index6")
    public ModelAndView index6(ModelAndView modelAndView, HttpServletRequest request) throws Exception{
        modelAndView.setViewName("/bigscreen/template6/index");
        glrIframeVideoMonitoringService.updateUserInfo(request);
        return modelAndView;
    }


}
